package com.dldata.devtools30.controller.sysform;

import com.alibaba.fastjson.JSON;
import com.dldata.devtools30.common.EnumUtils;
import com.dldata.devtools30.entity.DevtFormListtemplArgsEntity;
import com.dldata.devtools30.repository.common.DlBaseJdbcTemplate;
import com.dldata.devtools30.repository.sysform.DevtFormListtemplArgsDao;
import com.dldata.devtools30.repository.sysform.DevtFormListtemplTheaderDao;
import com.dldata.devtools30.utils.Result;
import com.dldata.devtools30.utils.StringUtil;
import com.dldata.devtools30.utils.Util;
import com.google.common.collect.Lists;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

/**

 */
@Controller
@RequestMapping(value = "/DevtFormListTemplArgsController")
public class DevtFormListTemplArgsController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());




    @Autowired
    private DevtFormListtemplArgsDao sysCrfFormListtemplArgsDao;

    @Autowired
    private DevtFormListtemplTheaderDao sysCrfFormListtemplTheaderDao;



    @Autowired
    DlBaseJdbcTemplate dlBaseJdbcTemplate;


    @RequestMapping(value = "/getAll")
    @ResponseBody
    public Result getAllSysForm(HttpServletRequest request, HttpServletResponse response, Model model, @RequestParam Map<String, Object> param){


        List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
        List <DevtFormListtemplArgsEntity> customTypeEntityList = Lists.newArrayList( sysCrfFormListtemplArgsDao.findAll());
        customTypeEntityList.stream().filter(
                sysCrfFormListtemplTheaderEntity -> {
                    return sysCrfFormListtemplTheaderEntity.getTempleid().equals(param.getOrDefault("pid", "").toString());
                }
        ).sorted(
                new Comparator<DevtFormListtemplArgsEntity>() {
                    @Override
                    public int compare(DevtFormListtemplArgsEntity o1, DevtFormListtemplArgsEntity o2) {
                        return o1.getXh()-o2.getXh();
                    }
                }
        ).forEach(
                (entity) -> {
                    Map<String, Object> tmpmap = (Map<String, Object>) JSON.parseObject(JSON.toJSONString(entity));
                    tmpmap.put("lxLable", EnumUtils.SEARCHLX.getFormValue(entity.getLx()).getLabel());
                    mapList.add(tmpmap);
                }
        );

        return Result.ok(mapList);
    }

    @RequestMapping(value = "save")
    @ResponseBody
    public Result save(DevtFormListtemplArgsEntity sysCrfFormEntity, HttpServletRequest request, HttpServletResponse response) throws  Exception{

        String result;
        try {
            if (sysCrfFormEntity.getId()==null||sysCrfFormEntity.getId().equals("")) {
                sysCrfFormEntity.setId(UUID.randomUUID().toString());
            }
            if(sysCrfFormEntity.getLxdata()!=null&&sysCrfFormEntity.getLxdata().trim().toLowerCase().startsWith("select")){
                sysCrfFormEntity.setLxdata("(sql)"+sysCrfFormEntity.getLxdata());
            }
//            sysCrfFormListtemplArgsDao.save(sysCrfFormEntity.getId(),sysCrfFormEntity);
            sysCrfFormListtemplArgsDao.save(sysCrfFormEntity);

            return Result.ok();

        } catch (Exception ex) {

            logger.error("【执行" + this.getClass().getName() + ".save() 方法失败 】异常：" + ex.getMessage());
            return Result.error("操作错误，请稍候再试！");
        }

    }

    @RequestMapping("delete")
    @ResponseBody
    public Result delete(String id,HttpServletRequest request, HttpServletResponse response) throws Exception{
        String result;

        try {
            sysCrfFormListtemplArgsDao.deleteById(id);

            return Result.ok();
        }
        catch (Exception ex){

            logger.error("【执行"+this.getClass().getName()+".delete() 方法失败 】异常："+ex.getMessage());
            return Result.error("操作错误，请稍候再试！");
        }

    }

    @RequestMapping(value = "toEdit")
    public String toEdit(String id,String pid, HttpServletRequest request, HttpServletResponse response, Model model) throws  Exception{

        String result;
        try {
            DevtFormListtemplArgsEntity sysCrfFormEntityTmp=new DevtFormListtemplArgsEntity();

            if(!StringUtil.isEmptyOrLength0(id)){
                 sysCrfFormEntityTmp=sysCrfFormListtemplArgsDao.findById(id).get();
            }else{
               //  List<SysFormListtemplArgsEntity> alldata = sysCrfFormListtemplArgsDao.getAllCloneData()
                List<DevtFormListtemplArgsEntity> alldata = Lists.newArrayList(sysCrfFormListtemplArgsDao.findAll());
                alldata= alldata.stream()
                        .filter(w->w.getTempleid().equals(pid)).collect(Collectors.toList());
                int xh = alldata.size() + 1;
                for (int i = 0; i < alldata.size(); i++) {
                    DevtFormListtemplArgsEntity entity = alldata.get(i);
                    xh=entity.getXh()>=xh?(entity.getXh()+1):xh;
                }
                sysCrfFormEntityTmp.setTempleid(pid);
                sysCrfFormEntityTmp.setXh(xh);
            }

            model.addAttribute("data",sysCrfFormEntityTmp);
            model.addAttribute("lxList", Util.getEnumMapNative(EnumUtils.SEARCHLX.class));
        } catch (Exception ex) {
            logger.error("【执行" + this.getClass().getName() + ".save() 方法失败 】异常：" + ex.getMessage());
        }
        return "thymeleaf/devtools30/sysform/v_SysFormListTemplArgsEdit";
    }

    @RequestMapping(value = "/getSqlData")
    @ResponseBody
    public List<Map<String,Object>> getSqlData(
            @RequestParam("argname") String argname,
            @RequestParam("templateId") String templateId,
            @RequestParam(value="mc", required=false) String mc,
            @RequestParam(value="tj", required=false) String tj,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception{


      //List <SysFormListtemplArgsEntity> customTypeEntityList = sysCrfFormListtemplArgsDao.getAllCloneData();
        List <DevtFormListtemplArgsEntity> customTypeEntityList =Lists.newArrayList(sysCrfFormListtemplArgsDao.findAll());
        DevtFormListtemplArgsEntity sysCrfFormFieldTemplateEntity1=customTypeEntityList.stream().filter(
                sysCrfFormListtemplTheaderEntity -> {
                    return sysCrfFormListtemplTheaderEntity.getArgname().equals(argname)
                            &&sysCrfFormListtemplTheaderEntity.getTempleid().equals(templateId);
                }
        ).collect(Collectors.toList()).get(0);


        String sql = sysCrfFormFieldTemplateEntity1.getLxdata();
        //有联动
        sql =sql.toLowerCase().indexOf("[#val]")>-1?sql.split("\\|")[0]:sql;

        sql=mc!=null?sql.replaceAll("\\[#tj]",mc):sql;

        sql=sql.replaceAll("\\[#tj]","");

        sql=tj !=null?sql.replaceAll("\\[#val]",tj):sql;

        sql=sql.replaceAll("\\[#val]","");

        sql=sql.replaceAll("\\(sql\\)","");

        List<Map<String,Object>> wdmList =  dlBaseJdbcTemplate.queryForList(sql);
        List<Map<String,Object>> resultList=new LinkedList<>();
        for (int i = 0; i < wdmList.size(); i++) {
            Map<String, Object> stringObjectMap = wdmList.get(i);
            Iterator<String> stringIterator = stringObjectMap.keySet().iterator();
            HashMap hashMapOne=new HashMap();
            while (stringIterator.hasNext()){
                String nextKeys = stringIterator.next();
                hashMapOne.put(nextKeys,stringObjectMap.get(nextKeys));
                hashMapOne.put(nextKeys.toLowerCase(),stringObjectMap.get(nextKeys));
                hashMapOne.put(nextKeys.toUpperCase(),stringObjectMap.get(nextKeys));
            }
            resultList.add(hashMapOne);
        }
        return resultList;
    }





}
